#include <stdio.h>
#include <string.h>
//下面都是本地文件
#include "../head/default.h"         //define 宏定义及static变量                                      
#include "../head/log.h"         //define 宏定义及static变量  


int f_my_strncpy(char *string, int n);
void f_logging(enum LogLevel level, const char *fmt, ...);

int f_my_check_ip(char *argv[], int role, int max_index, char addr[]) {
    //处理白名单 黑名单列表
    int mark = 0;
    char log_info[VAR_MAX_LEN];

    int ip_first_mark = 0;  //黑白名单 是否使用了掩码段
    for(int i = 0; i < max_index; i++) { 
        if (strstr(argv[i], ".0/24")) {
            f_my_strncpy(argv[i], (int)strlen(argv[i]) - 4);
            ip_first_mark = 1; 
        } else if (strstr(argv[i], ".0.0/16")) {
            f_my_strncpy(argv[i], (int)strlen(argv[i]) - 6);
            ip_first_mark = 1; 
        } else if (strstr(argv[i], ".0.0.0/8")) {
            f_my_strncpy(argv[i], (int)strlen(argv[i]) - 8);
            ip_first_mark = 1;
        }
        
        if (role == 1) { //白名单 
            if ((strcmp(argv[i], addr) == 0) || (ip_first_mark == 1 && strstr(addr, argv[i])) ) {
                mark = 0;    //只要再白名单里面就允许访问
                break;
            } else {
                mark = 1; //不在白名单里面, 就视为没有权限访问
            }
        } else { //黑名单
            if ((strcmp(argv[i], addr) == 0) || (ip_first_mark == 1 && strstr(addr, argv[i])) ) {
                memset(log_info, 0x00, sizeof(log_info));
                sprintf(log_info,"%s%s%s","SERVER --> The server uses a host-black-list and the client address[", addr, "] is in the blacklist.");
                f_logging(ERROR, log_info);
                mark = 1;
                break;
            }
        }
    }
    return mark;
}
